<?php

namespace app\common\model\mall\oper;

use think\Model;

class Msgtpl extends Model
{
    // 表名
    protected $name = 'mall_oper_msgtpl';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;

    // 追加属性
    protected $append = [
        'tplType_text'
    ];

    public function getTpltypeList()
    {
        return ['0' => __('Tpltype 0'),'1' => __('Tpltype 1'),'2' => __('Tpltype 2'),'3' => __('Tpltype 3')];
    }     

    public function getTpltypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['tplType']) ? $data['tplType'] : '');
        $list = $this->getTpltypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 根据模板代码获取模板或消息内容
     * @param string $tplCode 模板代码
     * @param string $find 查找字符
     * @param string $replace 替换字符
     * @return string 消息内容
     */
    public static function getMsgByTpl($tplCode, $find="", $replace=""){
            $rs = self::order('id asc')->select();
            $data = [];
            foreach ($rs as $key =>$v){
                if($v['tplContent']==''){
                    $data[$v['tplCode']] = $v;
                }else{
                    $v['content'] = htmlspecialchars_decode($v['tplContent']);
                    $v['tplContent'] = strip_tags(htmlspecialchars_decode($v['tplContent']));
                    $data[$v['tplCode']] = $v;
                }
            }
        //如果$find、$replace都为空，则返回模板，否则返回消息内容
        $msg = (isset($data[$tplCode])) ? ($find!="" && $replace!="" ? str_replace($find, $replace, $data[$tplCode]['tplContent']) : $data[$tplCode]['tplContent']) : null;
        return $msg;
    }

}
